﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Repo.Interfaces;

namespace Repo.Converters
{
    public class SPItemConverter
    {
        public static IList ConvertSharePointItemsToT(Type type, IEnumerable<SPListItem> spListItems)
        {
            return spListItems.Select(spListItem => ConvertSPItemToT(type, spListItem)).ToList();
        }

        private static object ConvertSPItemToT(Type type, SPListItem spListItem)
        { 
            var newT = Activator.CreateInstance(type);
            foreach (var property in type.GetProperties())
            {
                if (spListItem.Fields.ContainsFieldWithStaticName(property.Name))
                {
                    var value = spListItem[property.Name];
                    if (value != null)
                    {
                        if (typeof(IComplexFieldType).IsAssignableFrom(property.PropertyType))
                        {
                            var instance = Activator.CreateInstance(property.PropertyType);
                            property.SetValue(newT, ((IComplexFieldType)instance).SetInstanceValue(value), null);
                        }
                        else
                        {
                            switch (property.PropertyType.FullName)
                            {
                                case "System.Int32":
                                    property.SetValue(newT, FieldConverter.GetFieldValueAsInt(value), null);
                                    break;
                                case "System.Boolean":
                                    property.SetValue(newT, FieldConverter.GetFieldValueAsBool(value), null);
                                    break;
                                case "System.String":
                                    property.SetValue(newT, FieldConverter.GetFieldValueAsString(value), null);
                                    break;
                                case "System.DateTime":
                                    property.SetValue(newT, FieldConverter.GetFieldValueAsDateTime(value), null);
                                    break;
                            }
                        }
                    }
                }
            }
            return newT;
        }
    }
}
